import { Image, Text, TouchableOpacity, View, Dimensions } from "react-native";
import styles from "./index.style";
import { RadioButton } from "react-native-paper";
import {
  convertDateTimeToBeijingTime,
  convertToTodayTime,
} from "@/utils/time-utils";
import React, { useRef, useState } from "react";
import { ChatSession } from "@/types/chat-session";
import {router, useRouter} from "expo-router";
import { useTheme } from "@/contexts/ThemeContext";
import {useChatSessionActions, useChatSessionState} from "@/hooks/chat/chat-session";
import {useChatMessageActions} from "@/hooks/chat/chat-message";

// 定义菜单项类型
interface MenuItem {
  id: string;
  label: string;
  icon?: string;
  iconColor?: string;
  onPress: () => void;
}

// 定义菜单位置枚举
enum MenuPosition {
  ITEM_BOTTOM_DYNAMIC = "bottom",
}

// 定义上下文菜单服务接口
interface ContextMenuService {
  showMenu: (x: number, y: number, menuItems: MenuItem[], options: any) => void;
}

// 简单实现上下文菜单服务钩子
const useContextMenuService = (): ContextMenuService => {
  return {
    showMenu: (x, y, menuItems, options) => {
      console.log("显示菜单", { x, y, menuItems, options });
      // 实际实现会在这里显示菜单
    },
  };
};

// 获取屏幕尺寸
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get("window");
// 菜单最大宽度
const MENU_MAX_WIDTH = 280;
// 安全边距
const SAFE_MARGIN = 10;

interface SessionItemProps {
  session: ChatSession;
}

export default function SessionItem({ session }: SessionItemProps) {
  const { colors } = useTheme();
  const [isLongPressing, setIsLongPressing] = useState(false);
  const itemRef = useRef<View>(null);
  const contextMenuService = useContextMenuService();
  const { enableMultipleSelect, selectedSessions} = useChatSessionState();
  const {removeSelectedSession,addSelectedSession,changeMultipleSelectMode,updateSession,deleteSession} = useChatSessionActions();
  const {setCurrentChatDetailState, deleteAllMessages} = useChatMessageActions()

  const handlePress = () => {
    if (enableMultipleSelect) {
      if (selectedSessions.includes(session.sessionId)) {
        removeSelectedSession(session.sessionId);
      } else {
        addSelectedSession(session.sessionId);
      }
      return;
    }
    changeMultipleSelectMode(false);
    setCurrentChatDetailState(session);
    router.navigate("chat/chat-detail");
  };

  const menuOptions: MenuItem[] = [
    {
      id: "read-status",
      label: session.unreadCount === 0 ? "标记未读" : "标记已读",
      icon: "checkmark-circle-outline",
      onPress: async () => {
        await updateSession({
          sessionId: session.sessionId,
          unreadCount: session.unreadCount === 0 ? 1 : 0,
        });
      },
    },
    {
      id: "pin-status",
      label: session.pined ? "取消置顶" : "置顶该聊天",
      icon: "pin-outline",
      onPress: async () => {
        await updateSession({
          sessionId: session.sessionId,
          pined: !session.pined,
        });
      },
    },
    {
      id: "delete-chat",
      label: "删除该聊天",
      icon: "trash-outline",
      iconColor: colors.status.error,
      onPress: async () => {
        await deleteSession(session.sessionId);
        await deleteAllMessages(session.sessionId);
      },
    },
  ];

  const handleLongPress = (event: any) => {
    setIsLongPressing(true);
    if (!itemRef.current) {
      console.log("无法获取组件引用");
      return;
    }
    const { pageX, pageY } = event.nativeEvent;
    itemRef.current.measure((x, y, width, height, itemPageX, itemPageY) => {
      contextMenuService.showMenu(
        itemPageX + width / 2,
        itemPageY + height,
        menuOptions,
        {
          position: MenuPosition.ITEM_BOTTOM_DYNAMIC,
          touchInfo: { pageX, pageY },
          backgroundColor: colors.card.background,
          showShadow: true,
          maxWidth: MENU_MAX_WIDTH,
          verticalOffset: -40,
          menuStyle: {
            borderRadius: 12,
            padding: 0,
          },
          menuItemStyle: {
            padding: 12,
            marginVertical: 0,
          },
          onClose: () => {
            setIsLongPressing(false);
          },
        }
      );
    });
  };

  const sessionContent = (
    <View
      ref={itemRef}
      style={[
        styles.chatItem,
        {
          backgroundColor: isLongPressing
            ? colors.primary + "20"
            : colors.background,
          borderWidth: 1,
          borderColor: colors.border.divider
        },
      ]}
    >
      {enableMultipleSelect && (
        <View style={styles.radioBtn}>
          <RadioButton
            color={colors.primary}
            value={session.sessionId}
            status={
              selectedSessions.includes(session.sessionId)
                ? "checked"
                : "unchecked"
            }
            onPress={() => {
              if (selectedSessions.includes(session.sessionId)) {
                removeSelectedSession(session.sessionId);
              } else {
                addSelectedSession(session.sessionId);
              }
            }}
          />
        </View>
      )}
      <Image source={{ uri: session.sessionAvatar }} style={styles.avatar} />
      <View style={styles.chatContent}>
        <View style={styles.chatHeader}>
          <Text style={[styles.chatName, { color: colors.text.primary }]}>
            {session.sessionName}
          </Text>
          {session.pined && (
            <Text style={[styles.pinText, { color: colors.primary }]}>
              【置顶】
            </Text>
          )}
          <Text style={[styles.chatTime, { color: colors.text.secondary }]}>
            {convertToTodayTime(
              convertDateTimeToBeijingTime(session.updateTime)
            )}
          </Text>
        </View>
        {session.draft ? (
          <Text style={{ color: colors.text.secondary }} numberOfLines={1}>
            <Text style={{ color: colors.status.error }}>[草稿] </Text>
            <Text ellipsizeMode="tail">{session.draft}</Text>
          </Text>
        ) : session.lastMessage ? (
          <Text
            numberOfLines={1}
            ellipsizeMode="tail"
            style={{ color: colors.text.secondary }}
          >
            {session.lastMessage}
          </Text>
        ) : (
          <Text style={{ color: colors.text.secondary }}>{"[暂无消息]"}</Text>
        )}
      </View>
      {session.unreadCount > 0 && (
        <View
          style={[
            styles.unreadContainer,
            { backgroundColor: colors.status.badge },
          ]}
        >
          <Text style={[styles.unreadCount, { color: colors.text.white }]}>
            {session.unreadCount > 99 ? "99+" : session.unreadCount}
          </Text>
        </View>
      )}
    </View>
  );

  return (
    <TouchableOpacity
      activeOpacity={0.8}
      onPress={handlePress}
      onLongPress={handleLongPress}
    >
      {sessionContent}
    </TouchableOpacity>
  );
}
